<?php

namespace Zooclient;


use Selibra\Di\DI;
use Swoole\Coroutine;
use Zooclient\storage\SwooleTableZooStorage;
use Zooclient\storage\ZooDataStorageInterface;

/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */
class ZookeeperClient
{

    /**
     * @var \Zookeeper[]
     */
    private static array $zookeeper = [];

    /**
     * @var ZooDataStorageInterface
     */
    private static ZooDataStorageInterface $dataStorage;

    /**
     * @return ZooDataStorageInterface|false
     */
    public static function getDataStorage(): ZooDataStorageInterface|false
    {
        if (!isset(self::$dataStorage)) {
            // 不存在存储
            return false;
        }
        return self::$dataStorage;
    }

    /**
     * @param ZooDataStorageInterface $dataStorage
     */
    public static function setDataStorage(ZooDataStorageInterface $dataStorage): void
    {
        self::$dataStorage = $dataStorage;
    }


    /**
     * @param string $path
     * @param null $watcher_cb
     * @return array|null
     */
    public function getChildren(string $path, $watcher_cb = null): ?array
    {
        if (PHP_SAPI !== 'cli' || !self::getDataStorage()) {
            // 如果不是在cli模式下或者DataStore为初始化成功的情况下，直接连接，返回数据
            return $this->zookeeperInstance()->getChildren($path);
        }
        $storageKey = 'list-' . $path;
        if ($data = self::getDataStorage()->read($storageKey)) {
            return json_decode($data);
        }
        $value = $this->zookeeperInstance()->getChildren($path);
        go(function () use ($path, $watcher_cb) {
            $this->zookeeperInstance()->getChildren($path, function (...$argv) use ($watcher_cb) {
                // 重新设置
                $path = $argv[2];
                $storageKey = 'list-' . $path;
                $value = $this->zookeeperInstance()->getChildren($path);
                self::getDataStorage()->write($storageKey, json_encode($value));
                if (!empty($watcher_cb) && $watcher_cb instanceof \Closure) {
                    call_user_func($watcher_cb, $argv);
                }
            });
            // 通过while维持监听
            while (true) {
                // 通过sleep维持while
                Coroutine::sleep(10);
            }
        });
        self::getDataStorage()->write($path, json_encode($value));
        return $value;
    }


    public function get(string $path, $watcher_cb = null): ?string
    {
        if (PHP_SAPI !== 'cli' || !self::getDataStorage()) {
            // 如果不是在cli模式下或者DataStore为初始化成功的情况下，直接连接，返回数据
            return $this->zookeeperInstance()->get($path);
        }
        if ($data = self::getDataStorage()->read($path)) {
            return $data;
        }
        $value = $this->zookeeperInstance()->get($path);
        go(function () use ($path, $watcher_cb) {
            $this->zookeeperInstance()->get($path, function (...$argv) use ($watcher_cb) {
                // 重新设置
                $path = $argv[2];
                $value = $this->zookeeperInstance()->get($path);
                self::getDataStorage()->write($path, $value);
                if (!empty($watcher_cb) && $watcher_cb instanceof \Closure) {
                    call_user_func($watcher_cb, $argv);
                }
            });
            // 通过while维持监听
            while (true) {
                // 通过sleep维持while
                Coroutine::sleep(10);
            }
        });
        self::getDataStorage()->write($path, $value);
        return $value;
    }


    /**
     * @return \Zookeeper
     */
    public function zookeeperInstance(): \Zookeeper
    {
        return Connection::getConnection();
    }

}
